Building a Server Dashboard Application with ColdFusion-Powered Flex
Ben Forta
Macromedia Flex is a brand new server product, one that is poised to change the way you think about building rich and engaging user interfaces.
Yes, I did say "server." No, Flex does not compete with ColdFusion. Yes, Flex and ColdFusion are designed to work together.
Having now dispensed with the obligatory preliminaries, I'd like to present Macromedia Flex to the ColdFusion audience from a distinctly ColdFusion angle. And so in this article I will:
- Explain exactly what Flex is, from a ColdFusion user's perspective.
- Discuss the ColdFusion/Flex relationship.
- Walk you through a real (and really useful) example of a ColdFusion-powered Flex application (one that I have been using myself recently).
The first half of this article involves no hands-on examples and presents relevant information to any and all ColdFusion users, or rather, those interested in learning more about Flex and how it relates to what they do.
The second half of this article walks through and explains a real, albeit simple, ColdFusion-powered Flex application that reports ColdFusion server vitals in a dashboard interface. The ColdFusion dashboard is a useful little application, and one that nicely demonstrates Flex controls and their use with ColdFusion. But the dashboard application uses internal and undocumented ColdFusion functionality to expose administrative details. This code will work with ColdFusion MX and ColdFusion MX 6.1, but may not work with future versions of ColdFusion. Now that that is clear, read on.
And one other point to note before beginning. Flex is designed as enterprise software. As a ColdFusion developer, to be successful with Flex, Macromedia recommends that you are familiar with Java application development and deployment (WAR and EAR files) and that you use a structured approach to development. A structured approach with ColdFusion means that you adopt best practices, and write modular and tiered code, leveraging ColdFusion components (CFCs). Your team should also include an experienced object-oriented programmer and a person with user-centered application interface design skills. To learn about who Flex is designed for, check out David Wadhwani's article, Macromedia Flex: Is It the Right Fit for You? or the Flex Frequently Asked Questions.
Requirements
To try this example for yourself you will need:
Macromedia ColdFusion MX 6.1 (Standard or Enterprise on any platform supported by ColdFusion)
Macromedia Flex
(Installed and running on any server and platform supported by Flex. Note that the Flex trial is available on CD from the Macromedia store for $8.99. To learn more about the Flex trial, please read the Flex Frequently Asked Questions.)
The steps in this article do not use any specific development environment, so feel free to use whatever you are most comfortable with.
Sample files:
dashboard.zip (4K)
contains cfdb.mxml, cfdb.cfc, and struct2tree.as. I explain where to put these files in
the second half of the tutorial.
So, What Exactly Is Flex?
The best way to understand Flex is to think about how you build web applications right now. If you are a ColdFusion developer, or a developer who uses ASP, JSP, PHP, and the like, you probably build applications comprised of lots of linked pages. These pages contain client-code (at a minimum, HTML and JavaScript) as well as server-side code (CFML, SQL, and so forth). You probably try to separate content, or back-end data, from presentation, the front-end UI, but you still use both to create your application.
So, in the case of a ColdFusion page, a browser requests a CFML file, ColdFusion parses and processes the CFML in that file, and then returns client code to the browser. The browser renders the client code on the client, but it is ColdFusion on the server which embeds that client-code in the page. Or put differently, ColdFusion is a server that dynamically generates client-side code.
So why all this analysis? Simply put, Flex works in much the same way. Whereas ColdFusion (despite being somewhat client independent and agnostic) generates client-side HTML, Flex generates client-side Macromedia Flash SWF files. That was simply put, any maybe a bit too simplistic, but the analogy is sound; ColdFusion uses plain text files containing CFML tags to render browser content, and Flex uses text files containing MXML tags to render Macromedia Flash content. Compare the flows of both processes in figures 1 and 2.
Figure 1. A typical ColdFusion application flow
Figure 2. A typical Flex application flow
Flex is actually similar to ColdFusion in one other way. Flex, like ColdFusion, is a Java application. Flex is deployed on top of standard J2EE servers, such as Macromedia JRun, IBM Web Sphere, and so forth, in much the same way that you deploy ColdFusion, but more on that soon.
But that is where the similarities end. Unlike ColdFusion, Flex and its language, MXML, does not provide tags for database integration, sending and receiving e-mail, connecting to LDAP servers, or creating web services. Whereas ColdFusion is more of an all-purpose application development platform, Flex has a far more focused objective and a very specific goal. Flex is designed to facilitate the creation of rich and engaging presentation layers, letting developers create well-designed and optimally architected n-tier applications that adhere to standards and best practices. With Flex, coders can take advantage of the ubiquitous Flash platform from a very code-centric starting point, but what Flex generates is still Flash content. In other words, Flex is all about presentation and user interaction, and that is it.
All of the previous discussion means that Flex does not compete with ColdFusion; rather, Flex needs ColdFusion, or Java, or .NET, or something, anything, providing back-end integration. A Flex application needs a back end, and that back end can indeed be ColdFusion (as in Figure 2).
How do ColdFusion and Flex interact? The answer is that it depends; there are two distinct ways to go about using them together.
ColdFusion as a Flex Back End
So, Flex developers write MXML code to render user interfaces, and rely on external systems for any and all transactions, business logic, and back-end processing. How does Flex access these external systems? Flex provides tags that developers can use to:
- Invoke web services
- Make HTTP requests
- Call remote Java objects
It is worth noting that Flex itself does not really invoke web services or make HTTP calls or call remote Java objects, Flash does that. Flex generates a complete Flash application—a SWF file which runs in Macromedia Flash player—which makes all the back-end calls.
At this point, ColdFusion/Flash integration becomes obvious, Flex calls ColdFusion pages through HTTP requests, or invokes ColdFusion components (CFCs) as web services. You can use any ColdFusion code that you can invoke through HTTP or as a web service within Flex applications. To do this, you don't even have to have ColdFusion installed on the same server as Flex, although that configuration works too.
Figure 3. Application flow with ColdFusion as a Flex back end
In Figure 3, the flow works something like this:
- A user requests a Flex MXML URL.
- Flex generates a SWF, which it sends to the user.
- The user's Flash player executes the SWF.
- The SWF makes HTTP or web service calls from the player and obtains data.
- The Flex-generated SWF uses that data on the user's machine.
This type of integration delivers true n-tier applications, and is best suited for actual applications rather than embedded controls, for example.
This integration is also ideal for applications with multiple presentation layers. For example, if you needed a straight HTML version of your application in addition to the more engaging Flex version, you could simply provide multiple presentation interfaces to your back-end code. You would put your application logic, without any UI at all, in ColdFusion components; CFML pages would invoke the CFCs and render the HTML version of the application; and Flex MXML pages would render the Flash version of the application—the bonus is that both use the same back-end code.
ColdFusion-Generated Flex
Earlier I compared ColdFusion rendering client-side HTML to Flex rendering client-side Flash. But the integration just explained is not really the same. When ColdFusion renders client-side HTML, for example, the CFML pages programmatically render the HTML, perhaps even embedding dynamic data at the same time. This is quite different from the integration described in the "ColdFusion as a Flex Back End," where ColdFusion does not generating client-side Flash, it simply provides data to Flash, generated by Flex.
So can you use ColdFusion to dynamically generate Flash apps in much the same way as it can HTML? Yes, it can, through the Flex JSP Tag Library interface. Flex comes with JSP tags which you can use inside of JSP pages. JSP tags are much like CFML tags, except that they are written in JSP instead of in CFML. With Flex JSP tags, developers programmatically embed Flex tags such as the Tree tags or the Grid tag in their JSP pages so that when a user requests a JSP URL, the generated page has Flash embedded within it.
How does this help ColdFusion developers? ColdFusion code can call JSP tags too. CFML
has a tag named <CFIMPORT> that developers use to import or include
JSP tags; once imported, developers can use these tags like any other ColdFusion tag.
To be able to do this, ColdFusion and Flex must be installed on the same J2EE server. While this installation process is not terribly difficult, it is a manual process. This obviously requires ColdFusion Enterprise, and will not work with a Standalone ColdFusion installation, since the Standalone ColdFusion installation does not expose a J2EE server that could run Flex.
Figure 4. Application flow for ColdFusion-generated Flex
Figure 4 shows the workflow:
- A user requests a ColdFusion CFML URL.
- ColdFusion imports the Flex JSP tags.
- ColdFusion generates a page, which contains both HTML and a Flex-generated SWF, which it sends to the client.
- The page displays in the user's browser; an embedded SWF executes in the user's Flash player.
This type of integration is best for dynamically-generated content, such as a dynamically-generated and populated tree control. This type of integration is less suitable for full-blown applications.
Where To Use Flex
ColdFusion developers can think of Flex as being a replacement or an extension for the parts of the application that they would have written in HTML, JavaScript, DHTML, and so forth. But that does not mean that you should write every HTML application in Flex. In fact, while some applications are great potential Flex candidates, others are decidedly not.
- Flex is not intended to be used to replace specific form controls. For example, if you have an HTML form and use a pop-up calendar, do not replace the calendar with Flex code. The cost, the overhead, the bandwidth usage—none of those factors would make Flex an efficient option. Using Flex for whole parts of a form probably does not make sense. However, if you have a complex multipart form with lots of screens, form controls, and dynamic elements, then yes, Flex could be a good candidate.
- Applications involving raw reporting, data browsing, or working with large amounts of data—where the emphasis is less on the presentation and more on raw content—are also not Flex's sweet spot. While Flex provides controls, such as the data grid, that you can use within these applications, the overhead, performance, and amount of coding needed may make not be a fit for Flex.
- Flex is not designed to replace Flash. If you use Flash for complex animation or sophisticated design work, you'll still use Flash.
- Where Flex shines is in rich presentation of information, with an emphasis on "rich." Dashboard type applications are perfect for Flex, as are innovating ways to display and interact with specific data, such as shopping carts.
Of course, these are high-level generalizations, and there is no hard-and-fast rule here. The key is that Flex empowers developers to build rich and highly interactive user experiences. It is best suited for applications where this type of interaction is a requirement and where the project plan can accommodate the overhead associated with this type of experience.
Trying Flex
To demonstrate Flex and ColdFusion in perfect harmony, I'll guide you in building a dashboard application. This is a very simple application, but it is a useful one. I originally wrote it for my own use and it demonstrates much of what I've already discussed.
The application is a ColdFusion dashboard. With it, developers can monitor their ColdFusion Server settings: defined data sources and their availability, queue request time, server load, defined mappings, SERVER scope contents, and more. Of course, Flex has no knowledge of ColdFusion specifically, and so the application has two distinct parts to it, a ColdFusion side and a Flex side:
- cfdb.cfc is a ColdFusion component which exposes all of this information through web service calls. Place this file in any folder under the web root for your ColdFusion server. Note: Make sure you know the URL to it. You'll need to refer to it in the MXML code.
- cfdb.mxml is the Flex MXML which defines the user interface for the application. Place this file in any folder under the Flex application root.
- struct2tree.as is an ActionScript file that defines functions that cfdb.mxml needs; placed in the same folder as cfdb.mxml.
You can download these files in the sample files archive at the beginning of this tutorial.
For simplicity's sake, this application uses the first of the two integration methods described previously (ColdFusion as a Flex Back End). That is, you must put the CFC file on a ColdFusion server, but that doesn't have to be the Flex server; ColdFusion doesn't have to be running on the Flex server for this tutorial.
Note: This application is intended to be used on secure and trusted environments only. You'd never want to expose this much information on public facing servers.
The ColdFusion Dashboard Features a Tab Style Interface
Figure 5 shows a sample screen shot. As you can see, the ColdFusion Dashboard features a series of tabs, each of which provides different ColdFusion server information.
Figure 5. The ColdFusion dashboard features a tab style interface
There are five tabs in the dashboard:
- Stats displays server stats reported by the ColdFusion
GetMetricData()function. - Server displays the contents of the ColdFusion SERVER scope.
- Configuration displays several settings defined in the ColdFusion Administrator.
- Data Sources lists all defined data sources and whether or not they are available.
- Mappings displays the mappings in use by the ColdFusion server.
The tabs and contents are the ones that I needed for my own development. Adapt the application as best suits you using the techniques described below.
The cfdb.cfc file is a ColdFusion component that exposes five methods, one for each of the Dashboard tabs, as web services methods. The code is not complicated, but it is long, and so I'll not list it all here inline. However, you may download it from the beginning of this tutorial, in the Requirements section.
The method to populate the Server tab is very simple,
it contains a CFRETURN tag which returns the entire SERVER scope:
<!--- Get SERVER scope ---> <CFFUNCTION NAME="GetServerData" RETURNTYPE="struct" ACCESS="remote" OUTPUT="no"> <!--- Return SERVER ---> <CFRETURN SERVER> </CFFUNCTION>
Other methods are a bit more complicated. For example, the method to populate the Mappings tab calls the ColdFusion Service Factory and then formats the results as a ColdFusion query:
<!--- Get mappings --->
<!--- Get mappings --->
<CFFUNCTION NAME="GetMappings"
RETURNTYPE="query"
ACCESS="remote"
OUTPUT="no">
<!--- Define returned query --->
<CFSET VAR results=QueryNew("alias,path")>
<!--- Get "factory" --->
<CFSET VAR fObj=CreateObject("JAVA", "coldfusion.server.ServiceFactory")>
<!--- Get runtime service --->
<CFSET VAR rtService=fObj.getRuntimeService()>
<!--- Get mappings --->
<CFSET VAR mappings=rtService.getMappings()>
<!--- Loop through data sources --->
<CFLOOP COLLECTION="#mappings#" ITEM="i">
<!--- Add to query --->
<CFSET QueryAddRow(results)>
<CFSET QuerySetCell(results, "alias", i)>
<CFSET QuerySetCell(results, "path", mappings[i])>
</CFLOOP>
<!--- Return query --->
<CFRETURN results>
</CFFUNCTION>
I will not walk through all of this code here, but one technique worth noting is that you
should return data in as simple of a format as possible. The code in GetMappings() obtains
a structure from the Service factory, but then converts it into a query as working with
queries; it is easier for displaying grid-type data (this is true of any ColdFusion code,
not just code that Flex will consume).
All of the five methods in component cfdb.cfc accept no parameters, they only return data. You should probably write a simple CFML file to invoke each of these, dumping the output to verify that they work properly, before writing the Flex client.
The Flex Client Code
I've already explained that Flex applications are written in MXML, but this is actually not entirely true. Flex applications are written in MXML, an XML-based language, and ActionScript 2, an object-oriented scripting language that Flash uses. In fact, code written in MXML automatically generates ActionScript source code which is then compiled into a Flash SWF.
Why is this important? Because it means that your Flex applications can contain both MXML tags and ActionScript as in the examples below.
Open cfdb.mxml, which is part of dashboard.zip from the Requirements section. The cfdb.mxml is the core Flex application. I would have listed the entire code, but it is too long. As such, I've explained the code in snippets, below:
MXML is an XML language, and MXML pages must start with the XML header:
<?xml version="1.0"?>
The <mx:Applciation> tag defines the application, and likewise, the entire application
is between the opening and closing <mx:Application> and
</mx:Application)> tags:
<mx:Application marginBottom="5" marginLeft="5" marginTop="5" marginRight="5" initialize="update()" xmlns:mx="http://www.macromedia.com/2003/mxml" width="500" height="400">
The above code defines the size of the application in pixels, margins, and the location of the MXML language definition. I'll come back to the "initialize" attribute shortly.
The application calls the CFC methods as web services; the application defines these services
using the <mx:WebService> tag:
<!-- Define Web Service --> <mx:WebService id="dbSvc" wsdl="http://localhost:8500/cfdb/cfdb.cfc?wsdl" showBusyCursor="true"> <mx:operation name="GetStats" /> <mx:operation name="GetServerData" /> <mx:operation name="GetConfig" /> <mx:operation name="GetDataSources" /> </mx:WebService>
The wsdl attribute is the CFC WSDL URL. Change the path if needed.
The showBusyCursor="true" attribute
specifies to Flex that the mouse cursor should change to a stopwatch when the application
processes web service calls; this provides visual feedback to the customer.
The GetServerData() method returns a structure. The application populates a tree in
the Server tab that has a specific required format; thus, the code must convert a ColdFusion
structure into XML so the tree control can use it. With Flex, you can put code into external
files, and include them using the <mx:Script> tag; this tag is functionally similar
to the ColdFusion CFINCLUDE tag. The following line of code includes the struct2tree.as
file, which contains functions that perform the required conversion.
Note: I won't walk through the code in struct2tree.as in this article, but you may browse it yourself. It is a nice demonstration of ActionScript recursion.
<mx: Script source="struct2tree.as" />
The MXML <mx:Script> tag has another use too. With the <mx:Script> tag,
developers can embed ActionScript right inside of MXML pages. The <mx:Script> block
below defines two functions, the yesNoFormat() function and the update() function. The
yesNoFormat() function is much like the CFML function which has the same name; here, it
too returns a string "Yes" or "No" for boolean values.
// yesNoFormat() function
function yesNoFormat(bool) {
var result:String;
if (bool)
result="Yes"
else
result="No"
return result;
}
The update() function calls all of the five defined web service methods to update the display.
// update() all Web Service calls function
function update() {
dbSvc.GetStats();
dbSvc.GetServerData();
dbSvc.GetConfig();
dbSvc.GetDataSources();
dbSvc.GetMappings();
}
The initialize="update()" attribute in the <mx:Application> tag mentioned
previously triggers Flex to call the update() function automatically at application startup.
Next comes a bindings section in the file, but I'll skip that for now and come back to it shortly.
Next comes the UI itself. First is a title bar:
<!-- Title box -->
<mx:HBox>
<!-- Title -->
<mx:Label widthFlex="1"
text="ColdFusion Dashboard"
color="#FFFFFF"
fontSize="20" />
<!-- Update button -->
<mx:Button label="Update"
click="update()" />
</mx:HBox>
The title text is defined in a horizontal box, so that contents within it are displayed
side-by-side. The <mx:Label> tag is used to display a label (the title),
and <mx:Button> defines a button that calls the update()
function when a user presses it.
Note: Unlike in HTML, you cannot place text arbitrarily on a page, which is why you must use a tag to display title text.
The dashboard uses a tab interface, defined as follows:
<!-- Main screen --> <mx:TabNavigator> ... </mx:TabNavigator>
The individual tabs are defined in between <mx:TabNavigator> and </mx:TabNavigator> tags.
Figure 6. The Data Sources tab uses a DataGrid to display data source information
I am not going to walk through every line of code here, as much is repeated. But a good simple tab to start with is the Data Sources tab (Figure 6):
<!-- Data Sources tab -->
<mx:HBox label="Data Sources">
<!-- Data sources grid -->
<mx:DataGrid id="dsGrid"
editable="false"
heightFlex="1"
widthFlex="1">
<mx:columns>
<mx:Array>
<mx:DataGridColumn headerText="Name"
columnName="name" />
<mx:DataGridColumn headerText="Driver"
columnName="driver" />
<mx:DataGridColumn headerText="Verified"
columnName="verified" />
</mx:Array>
</mx:columns>
</mx:DataGrid>
</mx:HBox>
The code defines the actual tab using another box, the label of which is
used as the tab text. The <mx:DataGrid> tag defines the
data grid; it is named using the id attribute. Note that names must be
unique. By default, all data provided to a grid displays (this is preferable
for your app) in the sequence that the application returns the data (this
is not preferable for the user experience). So rather then using defaults,
you define the array of columns, and enumerate the individual columns using
the <mx:DataGridColumn> tag,
the headerText (the column title), and the columnName (actual retrieved
column name) for each. That is all you need to define the data grid. But
how does data actually get into the grid? That is where those bindings
come in; I'll get to those shortly.
You create the Mappings tab in exactly the same way.
Note: As an XML language, you must close all MXML tags, either with an end tag, or with a trailing slash (/).
The Configuration tab (Figure 7) uses a <mx:Grid> tag—not to be
confused with the data grid—to specifically align the element. The <mx:Grid> tag
is similar to the <TABLE> tag in HTML, the <mx:GridRow> tag is
like the HTML <TR> tag, and the <mx:GridItem> is like the
HTML <TD> tag. You use these tags to lay out all of the displayed data.
Figure 7. The Configuration tab uses a Grid to align text
The Server tab displays the SERVER scope contents in
a tree, which you define using the <mx:Tree> tag. When a user selects a tree member,
the application displays the value in a TextArea box below.
Figure 8. The Stats tab uses a DataGrid with a TextArea box below to display stat descriptions
The Stats tab is similar to the Data Source tab, but it contains a text area box at the bottom, which is populates with a description of the currently selected stat in the grid:
<!-- Stats tab -->
<mx:VBox label="Stats">
<!-- Stats grid -->
<mx:DataGrid id="statsGrid"
editable="false"
heightFlex="1"
widthFlex="1">
<mx:columns>
<mx:Array>
<mx:DataGridColumn headerText="Property"
columnName="property" />
<mx:DataGridColumn headerText="Vaue"
columnName="value" />
</mx:Array>
</mx:columns>
</mx:DataGrid>
<!-- Grid item description -->
<mx:TextArea wordWrap="true"
id="statDesc"
editable="false"
height="50"
widthFlex="1" />
</mx:VBox>
How does the application update the <mx:TextArea> box at the bottom of the screen
as a grid selection changes? And for that matter, how does any of the data that the web
service returns get into the appropriate UI controls? Now I'll go back and look at the <mx:Binding> tags
I skipped before.
Bindings are connections between controls. If you have ever used Microsoft Excel, you'll be familiar with the concept. Cells in a spreadsheet can refer to other cells so that changes and updates are automatically propagated to other cells as needed. Bindings work the same way. They associate a source with a destination and ensure that the destination is kept up to date as source contents change.
Bindings in Flex may be defined right inside of controls, as seen here:
<mx:DataGrid id="statsGrid"
editable="false"
heightFlex="1"
widthFlex="1"
dataProvider="{dbSvc.GetStats.result}">
The dataProvider attribute refers to the result of the GetStats method, so that anytime
GetStats returns data, the data grid updates automatically.
Note: Flex uses { and } to delimit expressions in the same way as CFML uses the pound sign (#).
Explicit binding works well, but when there are lots of bindings to lots of controls, all of those references can get hard to manage. In addition, binding this way make it impossible to bind a single control to multiple providers.
An alternate way to specify bindings is using the <mx:Binding> tag. cfdb.mxml has
a whole series of bindings defined, starting with:
<!-- Define the bindings -->
<mx:Binding source="dbSvc.GetStats.result"
destination="statsGrid.dataProvider" />
The <mx:Binding> tag takes a source and a destination, and ensures that if a change
occurs in the source, that that change is propagated to the specified destination. The rest
of the bindings work the same way, binding a source (some formatted using functions, including
the yesNoFormat() and struct2tree() functions) to destinations.
Note: You can define web services, bindings, scripts, and so forth, anywhere in your application, however, you may want to organize them as in cfdb.mxml.
And that is all there is to it. Each time the update() method executes—when a user clicks
the Update button or the application starts—Flex makes five web service calls to five defined
methods. Each time a web service call returns data—which may occur while Flex requests
other Web Service calls—the bindings route that data to the appropriate UI destination.
Note: When you browse cfdb.mxml in your browser, click the Update button each time you
want to update the display. One useful enhancement would be to include timer code that
executes the update() function on scheduled intervals. As there is no MXML timer control,
this would involve writing ActionScript code, which is beyond the scope of this article.
Where to Go From Here
As you can see, Flex makes creating rich interfaces easy (and even fun). The interface used in the ColdFusion Dashboard would be close to impossible to write in straight HTML, and downright painful to write in DHTML. But with Flex it's a breeze.
So where should you go from here?
So where should you go from here? Check out the following resources:
- Flex Developer Center
- Flex and ColdFusion Breeze Presentation by Ben Forta
- Building Rich Internet Applications with Macromedia Flex: A Flash Perspective by Nigel Pegg
- Macromedia Flex Application Life Cycle by Sean Schnoor
- Introduction to ColdFusion Components by Ben Forta
- ColdFusion Web Services topic page
Flex makes creating next-generation user experiences easy and fun. And ColdFusion is an ideal Flex back end. By combining Flex and ColdFusion, developers can create well-designed, structured, n-tier applications that leverage the back-end power and productivity that is uniquely ColdFusion, coupled with the front-end usability that is uniquely Flash.